package edu.kit.ksri.db.mturk.tests;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import edu.kit.ksri.db.mturk.plugins.performance.AbstractForecast;
import edu.kit.ksri.db.mturk.plugins.performance.DummyTimeConstraintsManager;
import edu.kit.ksri.db.mturk.plugins.performance.ProgressSnapshot;

/**
 * Copyright (c) 2010-2011 Karlsruhe Institute of Technology (KIT), Germany
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 * 
 * --------------------------------------------------------------------------
 * 
 * Software: CSP/WMV tool for dynamic quality management of microtasks
 * http://www.ksri.kit.edu/Upload/Users/PeopleClouds/HCOMP2011_An_extendable_toolkit_for_managing_quality_of_human-based_eServices.pdf
 * 
 * Organization: Karlsruhe Institute of Technology (KIT), Germany
 * http://www.kit.edu
 * 
 * Project: PeopleClouds project of the Karlsruhe Service Research Institute(KSRI)
 * http://www.ksri.kit.edu/Default.aspx?PageId=818
 * 
 * Contributing authors: David Bermbach, Sandra Rath, Pascal Wichmann, Robert Kern
 */
public class SimulationThread implements Runnable {

	/** which forecast shall be used */
	private AbstractForecast forecast;

	/** percentage of completed jobs when the deadline is reached */
	private double percentage;

	/** how many seconds shall elapse between snapshots */
	private int secondsBetweenSnapshots;

	/** the total number of hits */
	private int numberOfHITs;

	/** how many workers have to do the same task */
	private int numberOfAssignmentsPerHIT;

	/** size of the simulated active pool */
	private int activepoolsize;

	/** size of the simulated pending pool */
	private int pendingpoolsize;

	/** size of the simulated blocked pool */
	private int blockedpoolsize;

	/** size of the simulated unknown pool */
	private int unknownpoolsize;

	/** how long shall one assignment take */
	private int avgSecondsPerAssignment;

	/** time until the deadline has been reached in seconds */
	private int secondsUntilDeadline;

	/**
	 * flag which indicates whether the run method has already terminated (true)
	 * or not (false)
	 */
	private boolean done = false;

	/**
	 * 
	 * @param forecast
	 *            the {@link AbstractForecast} which shall be used
	 * @param secondsBetweenSnapshots
	 *            how many seconds shall elapse between snapshots
	 * @param numberOfHITs
	 *            the total number of hits
	 * @param numberOfAssignmentsPerHIT
	 *            how many workers have to do the same task
	 * @param activepoolsize
	 *            size of the simulated active pool
	 * @param pendingpoolsize
	 *            size of the simulated pending pool
	 * @param blockedpoolsize
	 *            size of the simulated blocked pool
	 * @param unknownpoolsize
	 *            size of the simulated unknown pool
	 * @param avgSecondsPerAssignment
	 *            how long shall one assignment take
	 * @param secondsUntilDeadline
	 *            time until the deadline has been reached in seconds
	 */
	public SimulationThread(AbstractForecast forecast,
			int secondsBetweenSnapshots, int numberOfHITs,
			int numberOfAssignmentsPerHIT, int activepoolsize,
			int pendingpoolsize, int blockedpoolsize, int unknownpoolsize,
			int avgSecondsPerAssignment, int secondsUntilDeadline) {
		super();
		this.forecast = forecast;
		this.secondsBetweenSnapshots = secondsBetweenSnapshots;
		this.numberOfHITs = numberOfHITs;
		this.numberOfAssignmentsPerHIT = numberOfAssignmentsPerHIT;
		this.activepoolsize = activepoolsize;
		this.pendingpoolsize = pendingpoolsize;
		this.blockedpoolsize = blockedpoolsize;
		this.unknownpoolsize = unknownpoolsize;
		this.avgSecondsPerAssignment = avgSecondsPerAssignment;
		this.secondsUntilDeadline = secondsUntilDeadline;
	}

	public void run() {
		try {
			Calendar end = Calendar.getInstance();
			end.setTime(new Date());
			end.add(Calendar.SECOND, this.secondsUntilDeadline);
			DummyTimeConstraintsManager d = new DummyTimeConstraintsManager(end
					.getTime(), forecast);
			DummyTimeConstraintsManager.startSimulation(d,
					this.secondsBetweenSnapshots, this.numberOfHITs,
					this.numberOfAssignmentsPerHIT, this.activepoolsize,
					this.pendingpoolsize, this.blockedpoolsize,
					this.unknownpoolsize, this.avgSecondsPerAssignment);
			while (!d.isDone())
				Thread.yield();
			List<ProgressSnapshot> snaps = d.getSnapshots();
			int completed = snaps.get(snaps.size() - 1)
					.getNumberOfAssignmentsCompleted();
			percentage = completed * 100.0
					/ (this.numberOfHITs * this.numberOfAssignmentsPerHIT);
			this.done = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return the percentage
	 */
	public double getPercentage() {
		return this.percentage;
	}

	/**
	 * @return the done
	 */
	public boolean isDone() {
		return this.done;
	}

}
